<?php

namespace app\common\controller;

use think\facade\Db;
use think\facade\Session;
use think\facade\Cache;
use think\helper\Str;
use app\common\variable\MsgCode;
use app\common\validate\User as UserValidate;
use app\common\validate\RealName as RealNameValidate;
use think\exception\ValidateException;
use app\common\model\User as UserModel;
use app\common\model\UserDisable as UserDisableModel;
use app\common\model\UserNotice as UserNoticeModel;
use app\common\model\UserRealName as UserRealNameModel;
use app\common\model\UserRealNameLog as UserRealNameLogModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\Resume as ResumeModel;
use app\common\model\Company as CompanyModel;
use app\common\model\CompanyCollection as CompanyCollectionModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\JobsDeliveryResume as JobsDeliveryResumeModel;
use app\common\model\CompanyBrowse as CompanyBrowseModel;
use app\common\model\InviteAninterview as InviteAninterviewModel;
use app\common\model\CompanyBlacklist as CompanyBlacklistModel;
use app\common\model\ResumeBlacklist as ResumeBlacklistModel;
use app\common\model\Area as AreaModel;
use app\common\model\PushTask as PushTaskModel;
use app\common\model\UserAvatarExamine as UserAvatarExamineModel;
use sendSms\SendSms;
use XYCms\Im as XYCMSIm;

/**
 * 
 */
class User extends Base
{
    public static function saveUserInfo($D)
    {
        $UserModel = UserModel::where(['id' => $D['uid']])->find();
        if ($UserModel)
            $D['id'] = $UserModel->id;
        if (!$UserModel->user && !empty($D['user'])) {
            $UserModel->user            =   $D['user'];
        } else {
            $D['user'] = '';
        }
        /**
         * 用户验证
         */
        try {
            validate(UserValidate::class)->scene('web_security')->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(), MsgCode::$error);
        }
        if (!empty($D['password'])) {
            if (UserModel::getPassword($UserModel->password_hash, $D['password']) == $UserModel->password)
                return parent::ajaxReturn('新密码与旧密码相同', MsgCode::$error);
            $passHash = Str::random(4);
            $UserModel->password_hash       =   $passHash;
            $UserModel->password            =   UserModel::getPassword($passHash, $D['password']);
        }
        $UserInfoModel = UserInfoModel::where(['uid' => $D['uid']])->find();


        $push=false;
        $AdminPushTaskModel=new PushTaskModel;
        $AdminPushTaskModel->event       =   'SystemWarning';
        $PushData=[
            'tpl'       =>'user_pictured_audit',
            'level'     =>'用户头像审核通知',
            'range'     =>'后台',
            'time'      =>date('Y-m-d H:i:s'),
//            'msg'       =>"用户【uid=>{$UserModel->mobile}】更换了头像，请审核。"
            'msg'       => "您有新的头像需要审核，用户UID:{$UserModel->id}上传了新头像，等待您的审核。"

        ];
        $AdminPushTaskModel->data        =  json_encode($PushData,JSON_UNESCAPED_UNICODE);

        // 存在未审核的头像则不修改
        $existAvatarExamine = UserAvatarExamineModel::where('uid', $UserInfoModel->uid)->where('status', 0)->find();
        if ($existAvatarExamine) {
            $existAvatarExamine->status = 2;
            $existAvatarExamine->reject_reason = '用户取消本次更改';
            $existAvatarExamine->save();
        }
        if (!empty($D['headimg'])) {
            if ($D['headimg'] != $UserInfoModel->headimg) {
                $examineData = [
                    'uid' => $UserInfoModel->uid,
                    'before_avatar' => $UserInfoModel->headimg,
                    'after_avatar' => $D['headimg'],
                    'status' => 0
                ];
                UserAvatarExamineModel::create($examineData);
                $push=true;
            }
        }


        if (!empty($D['nickname']))
            $UserInfoModel->nickname        =   base64_encode($D['nickname']);
        // 启动事务
        Db::startTrans();
        try {
            $UserModel->save();
            $UserInfoModel->save();
            if ($push){
                $AdminPushTaskModel->uid = $UserModel->id;
                $AdminPushTaskModel->save();
            }
            // 提交事务
            Db::commit();
            Cache::set('updateUser:' . $UserModel->id, true);
            return parent::ajaxReturn('已保存');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('保存失败，请重试', MsgCode::$error);
        }
    }
    public static function saveMobile($D)
    {
        /**
         * 用户验证
         */
        try {
            validate(UserValidate::class)->scene('edit_mobile')->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(), MsgCode::$error);
        }
        $SendSms = new SendSms;
        $SendSms->sendType = $D['is_username_type'];
        $SendSms->username = $D['mobile'];
        $SendSms->vcode = $D['vcode'];
        $SendSms->action = 'user/editMobile';
        if ($SendSms->verification()) {
            $UserModel = UserModel::where(['id' => $D['uid']])->find();
            $UserModel->mobile = $D['mobile'];
            if ($UserModel->save()) {
                $SendSms->delVcode();
                Cache::set('updateUser:' . $UserModel->id, true);
                return parent::ajaxReturn('手机号码已更改');
            } else {
                return parent::ajaxReturn('保存失败，请重试', MsgCode::$error);
            }
        } else {
            return parent::ajaxReturn($SendSms->getError(), MsgCode::$error);
        }
    }
    public static function saveEmail($D)
    {
        /**
         * 用户验证
         */
        try {
            validate(UserValidate::class)->scene('edit_email')->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(), MsgCode::$error);
        }
        if (empty($D['email']))
            return parent::ajaxReturn('邮箱不能为空', MsgCode::$error);
        $SendSms = new SendSms;
        $SendSms->sendType = $D['is_username_type'];
        $SendSms->username = $D['email'];
        $SendSms->vcode = $D['vcode'];
        $SendSms->action = 'user/editEmail';
        if ($SendSms->verification()) {
            $UserModel = UserModel::where(['id' => $D['uid']])->find();
            $UserModel->email = $D['email'];
            if ($UserModel->save()) {
                $SendSms->delVcode();
                Cache::set('updateUser:' . $UserModel->id, true);
                return parent::ajaxReturn('邮箱已更改');
            } else {
                return parent::ajaxReturn('保存失败，请重试', MsgCode::$error);
            }
        } else {
            return parent::ajaxReturn($SendSms->getError(), MsgCode::$error);
        }
    }
    public static function cancelAccount($D)
    {
        $UserModel = UserModel::where(['id' => $D['uid']])->find();
        $SendSms = new SendSms;
        $SendSms->sendType = 'mobile';
        $SendSms->username = $UserModel->mobile;
        $SendSms->vcode = $D['vcode'];
        $SendSms->action = 'user/cancelAccount';
        if ($SendSms->verification()) {
            $UserModel->status = 0;
            $disable_msg = config('basic.disable_msg');
            $UserModel->disable_msg = $disable_msg;
            $UserDisableModel = new UserDisableModel;
            $UserDisableModel->uid = $UserModel->id;
            $UserDisableModel->admin_uid = null;
            $UserDisableModel->disable_msg = $disable_msg;
            $UserDisableModel->status = 0;
            // 启动事务
            Db::startTrans();
            try {
                $UserModel->save();
                $UserDisableModel->save();
                // 提交事务
                Db::commit();
                $SendSms->delVcode();
                return parent::ajaxReturn('注销成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return parent::ajaxReturn('注销失败，请重试', -100);
            }
        } else {
            return parent::ajaxReturn($SendSms->getError(), MsgCode::$error);
        }
    }
    public static function editNotice($D)
    {
        $UserNoticeModel = UserModel::initNotice($D['uid']);
        $UserNoticeModel->new_notice = $D['new_notice'];
        $UserNoticeModel->disturb_mode = $D['disturb_mode'];
        $UserNoticeModel->start_time = $D['start_time'] . ':00';
        $UserNoticeModel->end_time = $D['end_time'] . ':00';
        $UserNoticeModel->delivery = $D['delivery'];
        $UserNoticeModel->recommend_like_jobs = $D['recommend_like_jobs'];
        $UserNoticeModel->new_article = $D['new_article'];
        if ($UserNoticeModel->save()) {
            Cache::set('updateUser:' . $D['uid'], true);
            return parent::ajaxReturn();
        } else {
            return parent::ajaxReturn('保存失败，请重试', MsgCode::$error);
        }
    }
    public static function statistics($D)
    {
        if ($D['role_type']) {
            if ($D['company_id']) {
                $jobs_sum = JobsModel::where(['company_id' => $D['company_id'], 'status' => 1])->whereNull('delete_time')->count();
                $resume_sum = JobsDeliveryResumeModel::where(['company_id' => $D['company_id']])->count();
                $not_resume_sum = JobsDeliveryResumeModel::where(['company_id' => $D['company_id'], 'status' => 0])->count();
                $invite_aninterview_sum = InviteAninterviewModel::where(['company_id' => $D['company_id']])->count();
                $interview_not = InviteAninterviewModel::where(['company_id' => $D['company_id'], 'status' => 3])->count();
                $company_browse_sum = CompanyBrowseModel::where(['company_id' => $D['company_id']])->count();
                $view = CompanyModel::where(['id' => $D['company_id']])->value('view');
                return parent::ajaxReturn('', MsgCode::$success, [
                    'jobs_sum'              =>  $jobs_sum,
                    'resume_sum'            =>  $resume_sum,
                    'not_resume_sum'        =>  $not_resume_sum,
                    'invite_aninterview_sum' =>  $invite_aninterview_sum,
                    'company_browse_sum'    =>  $company_browse_sum,
                    'view'                  =>  $view,
                    'interview_not'         =>  $interview_not,
                    'resume_efficiency'     => ($resume_sum - $not_resume_sum) > 0 ? round(($resume_sum - $not_resume_sum) / $resume_sum * 100) : 0
                ]);
            } else {
                return parent::ajaxReturn('', MsgCode::$error);
            }
        } else {
            if ($D['resume_id']) {
                $ResumeModel = ResumeModel::where(['id' => $D['resume_id']])->field('progress,update_time')->find();
                $resume_time = '';
                $progress = '--';
                if ($ResumeModel) {
                    $resume_time = $ResumeModel->update_time;
                    $progress = $ResumeModel->progress;
                }
                $collection = CompanyCollectionModel::where(['resume_id' => $D['resume_id']])->count();
                $jobs_sum = JobsDeliveryResumeModel::where(['resume_id' => $D['resume_id']])->whereNull('personal_delete_time')->count();
                $interview_not = JobsDeliveryResumeModel::where(['uid' => $D['uid'], 'status' => 3])->count();
                $interview = JobsDeliveryResumeModel::where(['uid' => $D['uid'], 'status' => 4])->count();
                $see = JobsDeliveryResumeModel::where(['resume_id' => $D['resume_id'], 'status' => 1])->whereNull('personal_delete_time')->count();
                $see = JobsDeliveryResumeModel::where(['resume_id' => $D['resume_id'], 'status' => 1])->whereNull('personal_delete_time')->count();
                $inappropriate = JobsDeliveryResumeModel::where(['resume_id' => $D['resume_id'], 'status' => 2])->whereNull('personal_delete_time')->count();
                return parent::ajaxReturn('', MsgCode::$success, [
                    'resume_time'           =>  $resume_time,
                    'progress'              =>  $progress,
                    'collection'            =>  $collection,
                    'jobs_sum'              =>  $jobs_sum,
                    'invite_aninterview_sum' =>  $interview_not + $interview,
                    'delivery'              =>  $jobs_sum,
                    'see'                   =>  $see,
                    'interview_not'         =>  $interview_not,
                    'inappropriate'         =>  $inappropriate,
                ]);
            } else {
                return parent::ajaxReturn('', MsgCode::$error);
            }
        }
    }
    public static function getMobile($User)
    {
        if (empty($User['id']))
            return parent::ajaxReturn('请先登录', MsgCode::$login);
        if ($User['role_type']) {
            $Find = CompanyModel::alias('company')->where(['company.id' => $User['company_id']])
                ->join('company_content content', 'content.cid = company.id', 'LEFT')
                ->field('company.title,company.stitle,content.contacts,content.contacts_mobile,content.contacts_tel')->find();
            if ($Find && $Find->title && $Find->contacts && $Find->contacts_mobile) {
                return parent::ajaxReturn('', MsgCode::$success, [
                    'name'   =>  $Find->stitle ? $Find->contacts . '·' . $Find->stitle : $Find->contacts . '·' . $Find->title,
                    'mobile' =>  $Find->contacts_mobile
                ]);
            } else {
                return parent::ajaxReturn('请先完善企业信息、企业联系人信息', MsgCode::$error);
            }
        } else {
            $Find = ResumeModel::alias('resume')->where(['resume.id' => $User['resume_id']])
                ->join('user user', 'user.id=resume.uid')
                ->field('resume.name,user.mobile')->find();
            if ($Find && $Find->name && $Find->mobile) {
                return parent::ajaxReturn('', MsgCode::$success, [
                    'name'   =>  $Find->name,
                    'mobile' =>  $Find->mobile
                ]);
            } else {
                return parent::ajaxReturn('请先完善简历信息', MsgCode::$error);
            }
        }
    }
    public static function getWechat($User)
    {
        if (empty($User['id']))
            return parent::ajaxReturn('请先登录', MsgCode::$login);
        if ($User['role_type']) {
            $Find = CompanyModel::alias('company')->where(['company.id' => $User['company_id']])
                ->join('company_content content', 'content.cid = company.id', 'LEFT')
                ->field('company.title,company.stitle,content.contacts,content.contacts_wechat')->find();
            if ($Find && $Find->title && $Find->contacts && $Find->contacts_wechat) {
                return parent::ajaxReturn('', MsgCode::$success, [
                    'name'   =>  $Find->stitle ? $Find->contacts . '·' . $Find->stitle : $Find->contacts . '·' . $Find->title,
                    'wechat' =>  $Find->contacts_wechat
                ]);
            } else {
                return parent::ajaxReturn('请先完善企业信息、企业联系人信息', MsgCode::$error);
            }
        } else {
            $Find = ResumeModel::where(['id' => $User['resume_id']])
                ->field('name,contact_wechat')->find();
            if ($Find && $Find->name && $Find->contact_wechat) {
                return parent::ajaxReturn('', MsgCode::$success, [
                    'name'   =>  $Find->name,
                    'wechat' =>  $Find->contact_wechat
                ]);
            } else {
                return parent::ajaxReturn('请先完善简历信息', MsgCode::$error);
            }
        }
    }
    public static function saveRealNameApply($D)
    {
        if (!isset($D['id_type']))
            return parent::ajaxReturn('请选择身份类型', MsgCode::$error);
        $scene = '';
        switch ($D['id_type']) {
            case 0:
                $scene = 'user';
                break;
            case 1:
                $scene = 'company';
                break;
            case 2:
                $scene = 'other';
                break;
            default:
                return parent::ajaxReturn('请选择身份类型', MsgCode::$error);
        }
        /**
         * 实名验证
         */
        try {
            validate(RealNameValidate::class)->scene($scene)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(), MsgCode::$error);
        };
        if ($scene === 'company' && !CompanyModel::where(['uid' => $D['uid']])->count())
            return parent::ajaxReturn('请先完善企业信息', MsgCode::$error);
        $UserRealNameModel = UserRealNameModel::where(['uid' => $D['uid'], 'id_type' => $D['id_type']])->find();
        if ($UserRealNameModel && $UserRealNameModel->status === 0)
            return parent::ajaxReturn('请勿重复提交申请', MsgCode::$error);
        if (!$UserRealNameModel)
            $UserRealNameModel = new UserRealNameModel;
        $UserRealNameModel->id_type     =   $D['id_type'];
        $UserRealNameModel->uid         =   $D['uid'];
        $UserRealNameModel->name        =   $D['name'];
        $UserRealNameModel->id_number   =   strtoupper($D['id_number']);
        if (!empty($D['img1']))
            $UserRealNameModel->img1        =   $D['img1'];
        if (!empty($D['img2']))
            $UserRealNameModel->img2        =   $D['img2'];
        $UserRealNameModel->status      =   0;
        $UserRealNameModel->ip          =   request()->ip();
        switch ($D['id_type']) {
            case 1:
            case 2:
                $UserRealNameModel->contacts    =   $D['contacts'];
                $UserRealNameModel->mobile      =   $D['mobile'];
                $UserRealNameModel->area1       =   $D['area'][0];
                $UserRealNameModel->area2       =   $D['area'][1];
                $UserRealNameModel->area3       =   $D['area'][2];
                $UserRealNameModel->address     =   $D['address'];
                if (!empty($D['img3']))
                    $UserRealNameModel->img3        =   $D['img3'];
                if (!empty($D['img4']))
                    $UserRealNameModel->img4        =   $D['img4'];
                if (!empty($D['img5']))
                    $UserRealNameModel->img5        =   $D['img5'];
                break;
        }
        $UserRealNameLogModel = new UserRealNameLogModel;
        $UserRealNameLogModel->status = 0;
        $UserRealNameLogModel->ip = request()->ip();
        $AdminPushTaskModel = new PushTaskModel;
        $AdminPushTaskModel->event       =   'SystemWarning';
        if ($D['id_type']) {
            $PushData = [
                'tpl'       => 'company_attestation',
                'level'     => '企业认证',
                'range'     => '后台',
                'time'      => date('Y-m-d H:i:s'),
//                'msg'       => 'UID:' . $UserRealNameModel->uid
                'msg'       => "您有新的企业认证需要审核，企业用户:{$UserRealNameModel->name}(UID:{$UserRealNameModel->uid})已提交认证，等待您的审核。"
            ];
        } else {
            $PushData = [
                'tpl'       => 'real_name',
                'level'     => '实名认证',
                'range'     => '后台',
                'time'      => date('Y-m-d H:i:s'),
//                'msg'       => 'UID:' . $UserRealNameModel->uid
                'msg'       => "您有新的实名认证需要审核，用户:{$UserRealNameModel->name}(UID:{$UserRealNameModel->uid})已提交认证，等待您的审核。"
            ];
        }
        $AdminPushTaskModel->data        =   json_encode($PushData, JSON_UNESCAPED_UNICODE);
        // 启动事务
        Db::startTrans();
        try {
            $UserRealNameModel->save();
            $UserRealNameLogModel->rid = $UserRealNameModel->id;
            $UserRealNameLogModel->save();
            $AdminPushTaskModel->save();
            // 提交事务
            Db::commit();
            return parent::ajaxReturn('提交成功，请耐心等待审核', MsgCode::$success, self::getRealNameApply(['id' => $UserRealNameModel->id]));
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('提交失败，请重试', MsgCode::$error);
        }
    }
    public static function getRealNameApply($where)
    {
        $Find = UserRealNameModel::where($where)->find();
        if ($Find) {
            $Find->log = UserRealNameLogModel::where(['rid' => $Find->id])->order('id desc')->limit(10)->select();
            if ($Find->id_type) {
                $Find->area = [$Find->area1, $Find->area2, $Find->area3];
                $Find->province_text = AreaModel::where(['id' => $Find->area1])->value('title');
                $Find->city_text = AreaModel::where(['id' => $Find->area2])->value('title');
                $Find->area_text = AreaModel::where(['id' => $Find->area3])->value('title');
                $Find->img1_url = $Find->img1 ? config('web.imgurl') . $Find->img1 : '';
                $Find->img2_url = $Find->img2 ? config('web.imgurl') . $Find->img2 : '';
                $Find->img3_url = $Find->img3 ? config('web.imgurl') . $Find->img3 : '';
                $Find->img4_url = $Find->img4 ? config('web.imgurl') . $Find->img4 : '';
                $Find->img5_url = $Find->img5 ? config('web.imgurl') . $Find->img5 : '';
            }
            if ($Find->status === 0 || $Find->status === 1)
                $Find->id_number = substr_replace($Find->id_number, '**********', 4, 10);
        }
        return $Find;
    }
    public static function getResumeBlacklist($uid)
    {
        $ResumeBlacklistModel = ResumeBlacklistModel::alias('b')->where(['b.uid' => $uid])->join('company company', 'company.uid=b.to_uid')->field('b.id,company.title as company_name')->order('b.id desc')->paginate(15);
        if ($ResumeBlacklistModel->items()) {
            return parent::ajaxReturn('', MsgCode::$success, $ResumeBlacklistModel);
        } else {
            return parent::ajaxReturn('暂无数据', MsgCode::$error);
        }
    }
    public static function getCompanyBlacklist($uid)
    {
        $CompanyBlacklistModel = CompanyBlacklistModel::alias('b')->where(['b.uid' => $uid])->join('resume resume', 'resume.uid=b.to_uid')->field('b.id,resume.id as resume_id,resume.name')->order('b.id desc')->paginate(15);
        if ($CompanyBlacklistModel->items()) {
            return parent::ajaxReturn('', MsgCode::$success, $CompanyBlacklistModel);
        } else {
            return parent::ajaxReturn('暂无数据', MsgCode::$error);
        }
    }
    public static function setCompanyBlacklist($D)
    {
        $CompanyBlacklistModel = new CompanyBlacklistModel;
        $backlist = [];
        $backlistIm = [];
        foreach ($D['list'] as $k => $v) {
            if (!CompanyBlacklistModel::where(['uid' => $D['uid'], 'to_uid' => $v])->count())
                $backlist[] = [
                    'uid'   =>  $D['uid'],
                    'to_uid' =>  $v
                ];
            $backlistIm[] = [
                'uid'   =>  $D['uid'],
                'to_uid' =>  $v
            ];
        }
        try {
            $imObj = new XYCMSIm;
            $imObj->blackContacts($backlistIm);
        } catch (\think\Exception $e) {
        }
        if (!empty($backlist) && !$CompanyBlacklistModel->saveAll($backlist))
            return parent::ajaxReturn('保存失败，请重试', MsgCode::$error);
        return parent::ajaxReturn();
    }
    public static function setResumeBlacklist($D)
    {
        $ResumeBlacklistModel = new ResumeBlacklistModel;
        $backlist = [];
        $backlistIm = [];
        foreach ($D['list'] as $k => $v) {
            if (!ResumeBlacklistModel::where(['uid' => $D['uid'], 'to_uid' => $v])->count())
                $backlist[] = [
                    'uid'   =>  $D['uid'],
                    'to_uid' =>  $v
                ];
            $backlistIm[] = [
                'uid'   =>  $D['uid'],
                'to_uid' =>  $v
            ];
        }
        try {
            $imObj = new XYCMSIm;
            $imObj->blackContacts($backlistIm);
        } catch (\think\Exception $e) {
        }
        if (!empty($backlist) && !$ResumeBlacklistModel->saveAll($backlist))
            return parent::ajaxReturn('保存失败，请重试', MsgCode::$error);
        return parent::ajaxReturn();
    }
    public static function cancelCompanyBlacklist($where)
    {
        $CompanyBlacklistModel = CompanyBlacklistModel::where($where)->find();
        if (!$CompanyBlacklistModel)
            return parent::ajaxReturn('取消失败，请重试', MsgCode::$error);
        if (CompanyBlacklistModel::where($where)->delete()) {
            try {
                $imObj = new XYCMSIm;
                $imObj->cancelBlackContacts($CompanyBlacklistModel->toArray());
            } catch (\think\Exception $e) {
            }
            return parent::ajaxReturn();
        } else {
            return parent::ajaxReturn('取消失败，请重试', MsgCode::$error);
        }
    }
    public static function cancelResumeBlacklist($where)
    {
        $ResumeBlacklistModel = ResumeBlacklistModel::where($where)->find();
        if (!$ResumeBlacklistModel)
            return parent::ajaxReturn('取消失败，请重试', MsgCode::$error);
        if (ResumeBlacklistModel::where($where)->delete()) {
            try {
                $imObj = new XYCMSIm;
                $imObj->cancelBlackContacts($ResumeBlacklistModel->toArray());
            } catch (\think\Exception $e) {
            }
            return parent::ajaxReturn();
        } else {
            return parent::ajaxReturn('取消失败，请重试', MsgCode::$error);
        }
    }
}
